package com.aierkeji.call.b2c.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aierkeji.call.b2c.contants.Contants;
import com.aierkeji.call.b2c.dao.jpa.AkjCallApprovalHistroDao;
import com.aierkeji.call.b2c.dao.jpa.AkjCallEnterpriseDao;
import com.aierkeji.call.b2c.dao.jpa.AkjCallRoleDao;
import com.aierkeji.call.b2c.dao.jpa.AkjCallUserDao;
import com.aierkeji.call.b2c.entity.AkjCallApprovalHistro;
import com.aierkeji.call.b2c.entity.AkjCallEnterprise;
import com.aierkeji.call.b2c.entity.AkjCallEnterpriseVo;
import com.aierkeji.call.b2c.entity.AkjCallRole;
import com.aierkeji.call.b2c.entity.AkjCallUser;
import com.aierkeji.call.b2c.entity.snap.AkjCallUserSnap;
import com.aierkeji.call.b2c.util.DateTimeUtils;
import com.aierkeji.call.b2c.util.ResultMapHelper;
import com.aierkeji.call.b2c.util.StringUtils;

@Service
public class AkjCallEnterpriseService {
	private final Logger log = LogManager.getLogger(getClass());
	@Autowired
	private AkjCallEnterpriseDao akjCallEnterpriseDao;

	@Autowired
	private AkjCallUserDao akjCallUserDao;
	
	@Autowired
	private AkjCallRoleDao akjCallRoleDao;
	
	@Autowired
	private AkjCallApprovalHistroDao akjCallApprovalHistroDao;
		
	
	/**
	 * 注册
	 * 
	 * @param map
	 * @return
	 */
	public Map<String, Object> registered(Map<String, Object> map) {
		try {
			String name = (String) map.get("name");
			AkjCallUser akjCallUser = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
			
			if (StringUtils.checkAnyNull(name)) {
				return ResultMapHelper.nullParamsResult();
			}
			AkjCallEnterprise akjCallEnterprise = akjCallEnterpriseDao.findByNameAndIsDelete(name,false);
			
			if(akjCallEnterprise == null || StringUtils.isEmpty(akjCallEnterprise.getName())) {
				
				AkjCallUser user 	= akjCallUserDao.findByAccountAndIsDelete(akjCallUser.getAccount(), false);
				List<AkjCallRole> roleList 	= akjCallRoleDao.findByCode(Contants.ROLE_ID_MANAGER);
				
				akjCallEnterprise = new AkjCallEnterprise();
				akjCallEnterprise.setName(name);
				akjCallEnterprise.setCreatedBy(AkjCallUserSnap.build(akjCallUser));
				akjCallEnterprise.setCreatedAt(DateTimeUtils.getCurrentTime());
				akjCallEnterprise.setUpdatedBy(AkjCallUserSnap.build(akjCallUser));
				akjCallEnterprise.setUpdatedAt(DateTimeUtils.getCurrentTime());
				akjCallEnterpriseDao.save(akjCallEnterprise);
				
				user.setEnterprise(akjCallEnterprise);
				user.setRoles(roleList);
				akjCallUserDao.save(user);
				SecurityUtils.getSubject().getSession().setAttribute("loginUser", user);
			}else {
				return ResultMapHelper.failure("当前企业名称已被注册！");
			}
		}catch (Exception e) {
			e.printStackTrace();
			return ResultMapHelper.failure("系统出错拉，注册企业失败");
		}
		return ResultMapHelper.success();
		
	}

	/**
	 * 加入企业
	 * @param map
	 * @return 
	 */
	public Map<String, Object> joinEnterprise(Map<String, Object> map) {
		try {
			Map<String, Object> sourceMap = new HashMap<String, Object>();
			
			String enterpriseId 	= (String) map.get("enterpriseId");
			String remark 			= (String) map.get("remark");
			
			if (StringUtils.checkAnyNull(enterpriseId)) {
				return ResultMapHelper.nullParamsResult();
			}
			AkjCallUser user = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
			if(user.getEnterprise() != null){
				return ResultMapHelper.failure("只能加入一家企业!");
			}
			
			AkjCallApprovalHistro ah =  akjCallApprovalHistroDao.findByApplyUserIdNoApprovalResult(AkjCallUserSnap.build(user));
			
			if(ah != null) {
				return ResultMapHelper.failure("申请成功,请耐心等候");
			}
			
			AkjCallEnterprise akjCallEnterprise = akjCallEnterpriseDao.findByIdAndIsDelete(Long.valueOf(enterpriseId),false);
			
			if(akjCallEnterprise == null || StringUtils.isEmpty(akjCallEnterprise.getName())) {
				return ResultMapHelper.failure("企业不存在！");
			}else{
				sourceMap.put("enterpriseManage", akjCallEnterprise.getCreatedBy());
				sourceMap.put("remark", remark);
				Map<String, Object> approvedMap = approvedUserJoinEnterprise(sourceMap);
				if(!approvedMap.get("status").equals("00")) {
					return ResultMapHelper.failure(approvedMap.get("msg").toString());
				}
			}
		}catch (Exception e) {
			log.error(e.getStackTrace());
			e.printStackTrace();
			return ResultMapHelper.failure("系统出错拉，加入企业失败");
		}
		return ResultMapHelper.success();
	}
	
	public Map<String, Object> approvedUserJoinEnterprise(Map<String, Object> map) {
		try {
			AkjCallUser user = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
			
			AkjCallApprovalHistro akjCallApprovalHistro = new AkjCallApprovalHistro();
			akjCallApprovalHistro.setApplyUserId(AkjCallUserSnap.build(user));
			akjCallApprovalHistro.setApprovalUserId((AkjCallUserSnap)map.get("enterpriseManage"));
			akjCallApprovalHistro.setRemark((String)map.get("remark"));
			akjCallApprovalHistro.setApplyAt(DateTimeUtils.getCurrentTime());
			akjCallApprovalHistroDao.save(akjCallApprovalHistro);
			
		}catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return ResultMapHelper.failure("加入企业审批出错!");
		}
		
		return ResultMapHelper.success();
		
	}
	
	public Map<String, Object> findEnterprise(Map<String, Object> map) {
		AkjCallEnterpriseVo vo = new AkjCallEnterpriseVo();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			
			AkjCallUser user = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
			
			BeanUtils.copyProperties(vo, user.getEnterprise());
			resultMap.put("data", vo);
		}catch (Exception e) {
			e.printStackTrace();
			return ResultMapHelper.failure("系统出错拉，查询失败");
		}
		return ResultMapHelper.success(resultMap);
	}

	public Map<String, Object> updateEnterprise(Map<String, Object> map) {
		String id 	= (String) map.get("id");
		String name 	= (String) map.get("name");
		AkjCallUser akjCallUser = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
		
		if (StringUtils.checkAnyNull(id,name)) {
			return ResultMapHelper.nullParamsResult();
		}
		
		AkjCallEnterprise enterprise = akjCallEnterpriseDao.findByIdAndIsDelete(Long.valueOf(id), false);
		enterprise.setName(name);
		enterprise.setCreatedAt(DateTimeUtils.getCurrentTime());
		enterprise.setUpdatedAt(DateTimeUtils.getCurrentTime());
		akjCallEnterpriseDao.save(enterprise);
		
		akjCallUser.setEnterprise(enterprise);
		SecurityUtils.getSubject().getSession().setAttribute("loginUser", akjCallUser);
		
		return ResultMapHelper.success();
	}

}
